package com.my.study.designPatterns.proxyPattern;

import javax.swing.*;
import java.awt.*;
import java.net.URL;

public class ImageProxy implements Icon {


    private ImageIcon imageIcon;

    private URL imageURL;

    private Thread retrievalThread;

    private boolean retrieving = false;

    public ImageProxy(URL imageURL) {
        this.imageURL = imageURL;
    }

    @Override
    public void paintIcon(Component c, Graphics g, int x, int y) {

        if(imageIcon != null){

            System.out.println(" not null=============================");
            imageIcon.paintIcon(c, g, x, y);
            System.out.println("---------" + imageIcon.getIconHeight() + "      " + imageIcon.getIconWidth());
        }else {

            System.out.println("null-------------");
            g.drawString("Loading CD cover, please wait!", x+30, y+30);
            if(!retrieving){
                retrieving = true;

                retrievalThread = new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try{
                            imageIcon = new ImageIcon(imageURL);
                            c.repaint();
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                    }
                });
                retrievalThread.start();
            }
        }
    }

    @Override
    public int getIconWidth() {
        if(imageIcon != null){
            return imageIcon.getIconWidth();
        }
        return 800;
    }

    @Override
    public int getIconHeight() {
        if(imageIcon != null){
            return imageIcon.getIconHeight();
        }
        return 600;
    }
}
